package eu.dicode.analysis.demonstrator;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

import eu.dicode.analysis.demonstrator.model.Topiccommand;
import eu.dicode.analysis.demonstrator.model.TopicsCommand;
import eu.dicode.analysis.demonstrator.service.TopicService;

@Controller
public class TopicController {

  private static final Logger log = LoggerFactory.getLogger(TopicController.class);
  private TopicService topicService;

  @RequestMapping(value = "/topic/list.html", method = RequestMethod.GET)
  public String showTopics(Model model) {
    model.addAttribute("topicsCommand", new TopicsCommand(topicService.getTopics()));
    return "topic/list";
  }

  @RequestMapping(value = "/topic/create.html", method = RequestMethod.GET)
  public String createTopic(Model model) {
    model.addAttribute("topic", new Topiccommand());
    return "topic/create";
  }

  @RequestMapping(value = "/topic/edit/{topicId}", method = RequestMethod.GET)
  public String editTopic(Model model, @PathVariable String topicId) {
    model.addAttribute("topic", this.topicService.getTopic(topicId));
    return "topic/create";
  }

  @RequestMapping(value = "/topic/edit/save.html", method = RequestMethod.POST)
  public String createTopic(HttpServletRequest request, Model model, @ModelAttribute("topic") Topiccommand newTopic) {
    if (!WebUtils.hasSubmitParameter(request, "cancel")) {
      this.topicService.addTopic(newTopic);
      model.addAttribute("topicsCommand", new TopicsCommand(this.topicService.getTopics()));
    }
    return "redirect:/topic/list.html";
  }

  @SuppressWarnings("unused")
  @Autowired
  private void setTopicService(TopicService topics) {
    this.topicService = topics;
  }
}
